<script setup lang="ts">
import { add, getById, getList, modify, removeById, show } from '@/api/generator'
import { onMounted, reactive, ref } from 'vue'
import { type PageInfo } from '@/api/base'
import { ElMessage, ElTable, type FormInstance, type Table } from 'element-plus'

interface GeneratorTable {
  id: number,
  createTime: string,
  updateTime: string,
  packageName: string,
  fullPackage: string,
  structName: string,
  tableName: string,
  title: string,
  icon: string,
  url: string,
  parentId: number,
  componentPath: string,
  columns: null
}
interface GeneratorColumn {
  uuid: number,
  fieldName: string,
  fieldType: string,
  fieldSize: number,
  fieldComment: string,
  isEdit: boolean,
  isShow: boolean,
  isSearch: boolean,
  component: string,
}

//页面相关
const generatorPage = reactive({
  tableData: { list: [] },
  visible: false,
  generatorData: {
    models: null,
    controller: null,
    service: null,
    repository: null,
    routers: null,
    sql: null
  },
  //加载列表
  getList: () => {
    getList(null, null).then((resp) => {
      console.log(resp.data);
      generatorPage.tableData = resp.data as PageInfo
    })
  },
  //修改信息
  editTable: (data: GeneratorTable) => {
    tableForm.tabsName = '表信息'
    getById(data.id).then(resp => {
      tableForm.form = resp.data
      fieldForm.form = resp.data.columns.map((v: any, i: number) => {
        v['uuid'] = i
        return v
      })
    })
    tableForm.visible = true
  },
  //删除信息
  removeTable: (data: GeneratorTable) => {
    console.log(data)
    removeById(data.id).then(() => {
      ElMessage.success({
        message: '删除成功'
      });
    })
  },
  //添加信息
  showTableDialog: () => {
    tableForm.tabsName = '表信息'
    tableForm.visible = true
    fieldForm.form = []
    tableForm.reset()
  },
  //下载生成内容
  generator: (data: GeneratorTable) => {

  },
  //显示生成内容
  showGeneraotr: (data: GeneratorTable) => {
    show(data.id).then(resp => {
      generatorPage.generatorData = resp.data
      generatorPage.visible = true
    })
  },
  //复制生成内容
  copy: (key: string) => {
    //@ts-ignore
    navigator.clipboard.writeText(generatorPage.generatorData[key] as string)
    ElMessage.success({
      message: `复制 ${key} 成功`
    })
  }
})


//表单相关
//表内容
const tableFormRef = ref<FormInstance>()
const tableForm = reactive({
  tabsName: '表信息',
  visible: false,
  form: {} as any | GeneratorTable,
  rules: {
    packageName: [{ required: false, message: "不能为空", trigger: 'blur' }],
    fullPackage: [{ required: false, message: "不能为空", trigger: 'blur' }],
    structName: [{ required: true, message: "不能为空", trigger: 'blur' }],
    tableName: [{ required: false, message: "不能为空", trigger: 'blur' }],
    tableComment: [{ required: true, message: "不能为空", trigger: 'blur' }],
    title: [{ required: false, message: "不能为空", trigger: 'blur' }],
    icon: [{ required: false, message: "不能为空", trigger: 'blur' }],
    url: [{ required: false, message: "不能为空", trigger: 'blur' }],
    componentPath: [{ required: false, message: "不能为空", trigger: 'blur' }],
  },
  reset: () => {
    tableForm.form = {
      id: null,
      createTime: null,
      updateTime: null,
      packageName: null,
      fullPackage: null,
      structName: null,
      tableName: null,
      tableComment: null,
      title: null,
      icon: null,
      url: null,
      parentId: null,
      componentPath: null,
      columns: null,
    }
    fieldForm.form.push({
      uuid: 0,
      fieldName: 'Id',
      fieldType: '*int',
      fieldSQLType: "int",
      fieldSize: 10,
      fieldComment: '主键编号',
      isEdit: false,
      isShow: true,
      isSearch: false,
      component: 'text',
    }, {
      uuid: 1,
      fieldName: 'CreateTime',
      fieldType: '*MyTime',
      fieldSQLType: "timestamp",
      fieldSize: 0,
      fieldComment: '创建时间',
      isEdit: false,
      isShow: true,
      isSearch: false,
      component: 'date',
    }, {
      uuid: 2,
      fieldName: 'UpdateTime',
      fieldType: '*MyTime',
      fieldSQLType: "timestamp",
      fieldSize: 0,
      fieldComment: '更新时间',
      isEdit: false,
      isShow: true,
      isSearch: false,
      component: 'date',
    })
  },
  nextForm: () => {
    tableFormRef.value!.validate((isValid) => {
      if (isValid) {
        tableForm.tabsName = '字段信息'
        return
      }
      ElMessage.error({
        message: '信息填写不完整！'
      })
    })
  },
  saveForm: () => {
    fieldFormRef.value!.validate(isValid => {
      if (!isValid) {
        ElMessage.error({
          message: "请完成表单填写！"
        })
        return
      }
      tableForm.form.columns = fieldForm.form.map(v => {
        delete v['uuid']
        return v
      })
      if (tableForm.form.id) {
        modify(tableForm.form).then(() => {
          ElMessage.success('修改表成功')
          generatorPage.getList()
          tableForm.visible = false
        })
        return
      }
      add(tableForm.form).then(() => {
        ElMessage.success('添加表成功')
        generatorPage.getList()
        tableForm.visible = false
      })
    })
  }
})

//字段内容
const fieldFormRef = ref<FormInstance>()
const fieldTableRef = ref()
const fieldForm = reactive({
  form: [] as any[],
  rules: {
    fieldName: [{ required: true, message: "不能为空", trigger: "blur" }],
    fieldType: [{ required: true, message: "不能为空", trigger: "blur" }],
    fieldSQLType: [{ required: true, message: "不能为空", trigger: "blur" }],
    fieldSize: [{ required: true, message: "不能为空", trigger: "blur" }],
    fieldComment: [{ required: true, message: "不能为空", trigger: "blur" }],
    isEdit: [{ required: false, message: "不能为空", trigger: "blur" }],
    isShow: [{ required: false, message: "不能为空", trigger: "blur" }],
    isSearch: [{ required: false, message: "不能为空", trigger: "blur" }],
    component: [{ required: true, message: "不能为空", trigger: "blur" }],
  },
  //添加一行
  addRow: () => {
    fieldForm.form.push({
      uuid: fieldForm.form.length,
      fieldName: null,
      fieldType: '*string',
      fieldSQLType: "varchar",
      fieldSize: 10,
      fieldComment: null,
      isEdit: true,
      isShow: true,
      isSearch: null,
      component: 'text',
    } as any | GeneratorColumn)
    console.log(fieldForm)
  },
  //删除选中行
  removeRow: () => {
    const val = fieldTableRef.value.getSelectionRows()

    fieldForm.form = fieldForm.form.filter(v => {

      for (const t of val) {
        if (t.uuid < 3) continue
        if (v.uuid === t.uuid) {
          return false
        }
      }
      return true
    })

  }

})


//页面加载完成
onMounted(() => {
  //加载列表
  generatorPage.getList()
  //重新加载一下表单
  tableForm.reset()
})

</script>

<template>
  <el-container>
    <el-row>
      <el-col style="margin: 20px;">
        <el-button type="primary" @click="generatorPage.showTableDialog">添加</el-button>
      </el-col>
      <el-col>
        <el-table :data="generatorPage.tableData.list" stripe>
          <el-table-column header-align="center" align="center" width="50" label="id" prop="id"></el-table-column>
          <el-table-column header-align="center" align="center" label="包名" prop="packageName"></el-table-column>
          <el-table-column header-align="center" align="center" width="120" label="结构体名"
            prop="structName"></el-table-column>
          <el-table-column header-align="center" align="center" width="120" label="表明"
            prop="tableName"></el-table-column>
          <el-table-column header-align="center" align="center" label="表备注" prop="tableComment"></el-table-column>
          <el-table-column header-align="center" align="center" label="菜单名" prop="title"></el-table-column>
          <el-table-column header-align="center" align="center" label="菜单图标" prop="icon"></el-table-column>
          <el-table-column header-align="center" align="center" label="地址" prop="url"></el-table-column>
          <el-table-column header-align="center" align="center" label="组件地址" prop="componentPath"></el-table-column>
          <el-table-column header-align="center" align="center" width="300" label="操作">
            <template #default="scope">
              <el-button @click="generatorPage.showGeneraotr(scope.row)">预览</el-button>
              <el-button type="primary" @click="generatorPage.generator(scope.row)">下载</el-button>
              <el-button type="warning" @click="generatorPage.editTable(scope.row)">修改</el-button>
              <el-button type="danger" @click="generatorPage.removeTable(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
  </el-container>

  <!-- 预览 -->
  <el-dialog v-model="generatorPage.visible" :width="1200">
    <el-tabs model-value="models" type="border-card">
      <el-tab-pane label="models" name="models">
        <el-row justify="end">
          <el-col :span="2">
            <el-button @click="generatorPage.copy('models')">复制</el-button>
          </el-col>
        </el-row>
        <pre>
        {{ generatorPage.generatorData.models }}
      </pre>
      </el-tab-pane>
      <el-tab-pane label="controller" name="controller">
        <el-row justify="end">
          <el-col :span="2">
            <el-button @click="generatorPage.copy('controller')">复制</el-button>
          </el-col>
        </el-row>
        <pre>
        {{ generatorPage.generatorData.controller }}
      </pre>
      </el-tab-pane>
      <el-tab-pane label="service" name="service">
        <el-row justify="end">
          <el-col :span="2">
            <el-button @click="generatorPage.copy('service')">复制</el-button>
          </el-col>
        </el-row>
        <pre>
        {{ generatorPage.generatorData.service }}
      </pre>
      </el-tab-pane>
      <el-tab-pane label="repository" name="repository">
        <el-row justify="end">
          <el-col :span="2">
            <el-button @click="generatorPage.copy('repository')">复制</el-button>
          </el-col>
        </el-row>
        <pre class="code">
        {{ generatorPage.generatorData.repository }}
      </pre>
      </el-tab-pane>

      <el-tab-pane label="routers" name="routers">
        <el-row justify="end">
          <el-col :span="2">
            <el-button @click="generatorPage.copy('routers')">复制</el-button>
          </el-col>
        </el-row>
        <pre>
        {{ generatorPage.generatorData.routers }}
      </pre>
      </el-tab-pane>
      <el-tab-pane label="sql" name="sql">
        <el-row justify="end" align="center">
          <el-col :span="8"><el-text type="danger" style="line-height: 32px">SQL生成不完整，需要手动改动一下！</el-text></el-col>
          <el-col :span="2">
            <el-button @click="generatorPage.copy('sql')">复制</el-button>
          </el-col>
        </el-row>
        <pre>
        {{ generatorPage.generatorData.sql }}
      </pre>
      </el-tab-pane>
    </el-tabs>
  </el-dialog>

  <el-dialog v-model="tableForm.visible" :width="1200">
    <el-tabs v-model="tableForm.tabsName" type="border-card">
      <el-tab-pane label="表信息" name="表信息" disabled>
        <el-form ref="tableFormRef" :model="tableForm.form" :rules="tableForm.rules" label-width="100">
          <el-row>
            <el-col :span="12">
              <el-form-item prop="packageName" label="包名：">
                <el-input v-model="tableForm.form.packageName" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="fullPackage" label="全包名：">
                <el-input v-model="tableForm.form.fullPackage" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="structName" label="结构体名：">
                <el-input v-model="tableForm.form.structName" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="tableName" label="表名：">
                <el-input v-model="tableForm.form.tableName" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="tableComment" label="表备注：">
                <el-input v-model="tableForm.form.tableComment" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="title" label="菜单名：">
                <el-input v-model="tableForm.form.title" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="icon" label="图标：">
                <el-input v-model="tableForm.form.icon" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="parentId" label="url：">
                <el-input v-model.number="tableForm.form.url" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="parentId" label="上级ID：">
                <el-input v-model.number="tableForm.form.parentId" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="componentPath" label="组件路径：">
                <el-input v-model="tableForm.form.componentPath" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <el-row justify="center">
          <el-col :span="1"><el-button type="primary" @click="tableForm.nextForm">下一步</el-button></el-col>
        </el-row>
      </el-tab-pane>
      <el-tab-pane label="字段信息" name="字段信息" disabled>

        <el-row>
          <el-button type="success" @click="fieldForm.addRow">添加</el-button>
          <el-button type="danger" @click="fieldForm.removeRow">删除</el-button>
        </el-row>

        <el-form ref="fieldFormRef" :model="fieldForm" :rules="fieldForm.rules">
          <el-table ref="fieldTableRef" :data="fieldForm.form">
            <el-table-column type="selection" />
            <el-table-column label="字段名">
              <template #default="{ $index }">
                <el-form-item class="el-form-item-custom" align="center" header-align="center"
                  :prop="`form[${$index}].fieldName`" :rules="fieldForm.rules.fieldName">
                  <el-input v-model="fieldForm.form[$index].fieldName" :disabled="$index < 3" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="SQL类型">
              <template #default="{ $index }">
                <el-form-item class="el-form-item-custom" align="center" header-align="center"
                  :prop="`form[${$index}].fieldName`" :rules="fieldForm.rules.fieldSQLType">
                  <el-select v-model="fieldForm.form[$index].fieldSQLType" :disabled="$index < 3">
                    <el-option value="int">int</el-option>
                    <el-option value="varchar" default>varchar</el-option>
                    <el-option value="text">text</el-option>
                    <el-option value="date">date</el-option>
                    <el-option value="datetime">datetime</el-option>
                    <el-option value="timestamp">timestamp</el-option>
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="字段类型">
              <template #default="{ $index }">
                <el-form-item class="el-form-item-custom" align="center" header-align="center"
                  :prop="`form[${$index}].fieldName`" :rules="fieldForm.rules.fieldType">
                  <el-select v-model="fieldForm.form[$index].fieldType" :disabled="$index < 3">
                    <el-option value="*int">*int</el-option>
                    <el-option value="*string" default>*string</el-option>
                    <el-option value="*bool">*bool</el-option>
                    <el-option value="*rune">*rune</el-option>
                    <el-option value="*float32">*float32</el-option>
                    <el-option value="*float64">*float64</el-option>
                    <el-option value="*MyTime">*MyTime</el-option>
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="字段大小">
              <template #default="{ $index }">
                <el-form-item class="el-form-item-custom" align="center" header-align="center"
                  :prop="`form[${$index}].fieldSize`" :rules="fieldForm.rules.fieldSize">
                  <el-input type="number" v-model.number="fieldForm.form[$index].fieldSize" :disabled="$index < 3" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="字段备注">
              <template #default="{ $index }">
                <el-form-item class="el-form-item-custom" align="center" header-align="center"
                  :prop="`form[${$index}].fieldComment`" :rules="fieldForm.rules.fieldComment">
                  <el-input v-model="fieldForm.form[$index].fieldComment" :disabled="$index < 3" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="编辑" width="70">
              <template #default="{ $index }">
                <el-form-item class="el-form-item-custom" align="center" header-align="center"
                  :prop="`form[${$index}].isEdit`" :rules="fieldForm.rules.isEdit">
                  <el-checkbox checked v-model="fieldForm.form[$index].isEdit" :disabled="$index < 3" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="显示" width="70">
              <template #default="{ $index }">
                <el-form-item class="el-form-item-custom" align="center" header-align="center"
                  :prop="`form[${$index}].isShow`" :rules="fieldForm.rules.isShow">
                  <el-checkbox checked v-model="fieldForm.form[$index].isShow" :disabled="$index < 3"></el-checkbox>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="搜索" width="70">
              <template #default="{ $index }">
                <el-form-item class="el-form-item-custom" align="center" header-align="center"
                  :prop="`form[${$index}].isSearch`" :rules="fieldForm.rules.isSearch">
                  <el-checkbox v-model="fieldForm.form[$index].isSearch" :disabled="$index < 3"></el-checkbox>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="组件">
              <template #default="{ $index }">
                <el-form-item class="el-form-item-custom" align="center" header-align="center"
                  :prop="`form[${$index}].component`" :rules="fieldForm.rules.component">
                  <el-select v-model="fieldForm.form[$index].component" :disabled="$index < 3">
                    <el-option value="text">文本</el-option>
                    <el-option value="number">数字</el-option>
                    <el-option value="date">日期</el-option>
                    <el-option value="select">下拉框</el-option>
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
          </el-table>
        </el-form>
        <el-row justify="center" style="margin-top: 10px;">
          <el-col :span="4">
            <el-button @click="tableForm.tabsName = '表信息'">上一步</el-button>
            <el-button type="primary" @click="tableForm.saveForm">保存</el-button>
          </el-col>
        </el-row>
      </el-tab-pane>
    </el-tabs>
  </el-dialog>
</template>

<style lang="scss" scoped>
.el-form-item-custom {
  padding: 0;
  margin: 15px 0;

  .el-form-input {
    padding: 0;
    margin: 0;
  }
}

.code {
  // white-space: wrap;
  // text-wrap: wrap;
}
</style>
